import { forwardRef, useImperativeHandle, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, Drawer, Form, FormProps, Input, InputNumber, Radio, Space } from 'antd';

import { store } from '@/store';

import { noSpaceValidator } from '@/config/rule';
import { SysCfgEnvObj, SysCfgTypeObj } from '@/enum/cfg';
import {
  systemConfigAdd,
  systemConfigUpdate
} from '@/services/base/jichumokuaixitongpeizhixinxijiekou';

type EditOpenBaseArgs = {
  groupData: BASE.SysWebSystemConfigGroupVO;
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BASE.SystemConfig;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BASE.SystemConfig;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const submit = useRequest(
    async (values) => {
      const query = {
        ...values,
        configModule: args?.groupData.groupName
      };

      if (args?.type === 'edit' && args.rowData) {
        query.id = args.rowData.id;
      }

      await (args?.type === 'edit' ? systemConfigUpdate(query) : systemConfigAdd(query));

      args?.onSuccess?.();
      setOpen(false);

      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(async () => {
          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            // 回填数据
            form.setFieldsValue({
              ...arg.rowData
            });
          } else {
            form.resetFields();
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Drawer
      title={
        {
          add: '新增配置',
          edit: '编辑配置',
          detail: '配置详情'
        }[args?.type as string]
      }
      extra={
        <Space>
          <Button
            type="primary"
            loading={submit.loading}
            disabled={submit.loading}
            onClick={onSave}
          >
            保存
          </Button>
          <Button onClick={onCancel} disabled={submit.loading}>
            取消
          </Button>
        </Space>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item
          label="配置名称"
          name="configName"
          rules={[
            {
              required: true,
              message: '此项必填'
            },
            {
              validator: noSpaceValidator
            },
            {
              validator: async (_, value) => {
                // 不对空值校验
                if (value === '' || value === null || typeof value === 'undefined') {
                  return;
                }

                const max = 200;

                if (String(value).length > max) {
                  throw new Error(`最多只能输入${max}个字符`);
                }
              }
            }
          ]}
        >
          <Input placeholder="请输入配置名称" />
        </Form.Item>
        <Form.Item
          label="配置编码"
          name="configCode"
          rules={[
            {
              required: true,
              message: '此项必填'
            },
            {
              validator: noSpaceValidator
            },
            {
              validator: async (_, value) => {
                // 不对空值校验
                if (value === '' || value === null || typeof value === 'undefined') {
                  return;
                }

                const max = 200;

                if (String(value).length > max) {
                  throw new Error(`最多只能输入${max}个字符`);
                }
              }
            }
          ]}
        >
          <Input placeholder="请输入配置编码" />
        </Form.Item>
        <Form.Item
          label="配置环境"
          name="configEnvironment"
          rules={[{ required: true, message: '请选择配置环境' }]}
        >
          <Radio.Group>
            {Array.from(SysCfgEnvObj).map(([key, value]) => (
              <Radio value={key} key={key}>
                {value.text}
              </Radio>
            ))}
          </Radio.Group>
        </Form.Item>
        <Form.Item
          label="配置类型"
          name="configType"
          rules={[{ required: true, message: '请选择配置类型' }]}
        >
          <Radio.Group
            onChange={() => {
              form.setFieldsValue({
                configValue: undefined
              });
            }}
          >
            {Array.from(SysCfgTypeObj).map(([key, value]) => (
              <Radio value={key} key={key}>
                {value.text}
              </Radio>
            ))}
          </Radio.Group>
        </Form.Item>
        <Form.Item label="配置值" name="configValue">
          <Input placeholder="请输入配置值" />
        </Form.Item>
        <Form.Item label="配置校验正则" name="configCheckRegular">
          <Input placeholder="请输入配置校验正则" />
        </Form.Item>
        <Form.Item label="排序" name="sortNo">
          <InputNumber step={1} />
        </Form.Item>
        <Form.Item label="配置说明" name="configExplain">
          <Input.TextArea placeholder="请输入配置说明" />
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default forwardRef(Edit);
